package com.hd.crdao.base;

import android.app.AlertDialog;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.support.annotation.NonNull;

import com.baidu.mapapi.SDKInitializer;
import com.hd.crdao.BuildConfig;
import com.hd.crdao.utils.ALog;
import com.hd.crdao.utils.PackageInfoUtils;
import com.hd.crdao.wrapper.AppCrashHandleCallback;
import com.hss01248.dialog.StyledDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreater;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreater;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.squareup.leakcanary.LeakCanary;
import com.taobao.sophix.PatchStatus;
import com.taobao.sophix.SophixManager;
import com.taobao.sophix.listener.PatchLoadStatusListener;
import com.tencent.bugly.crashreport.CrashReport;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import cn.jpush.android.api.JPushInterface;
import okhttp3.OkHttpClient;


/**
 * 描述	      全局单例
 * 描述	      易错点:需要在清单文件里面进行配置
 */
public class MyApplication extends Application {

    private static Context mContext;
    private static Handler mMainThreadHandler;
    private static int mMainThreadId;

    //  public LocationService locationService;


    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        initSophix();
    }

    public HashMap<String, String> getMemProtocolCacheMap() {
        return memProtocolCacheMap;
    }

    private HashMap<String, String> memProtocolCacheMap = new HashMap<>();

    /**
     * 得到上下文
     *
     * @return
     */
    public static Context getContext() {
        return mContext;
    }

    /**
     * 得到主线程里面的创建的一个hanlder
     *
     * @return
     */
    public static Handler getMainThreadHandler() {
        return mMainThreadHandler;
    }

    /**
     * 得到主线程的线程id
     *
     * @return
     */
    public static int getMainThreadId() {
        return mMainThreadId;
    }

    @Override
    public void onCreate() {//程序的入口方法
        super.onCreate();
        //上下文
        mContext = getApplicationContext();

        //主线程的Handler
        mMainThreadHandler = new Handler();

        //主线程的线程id
        mMainThreadId = android.os.Process.myTid();
        initOkhttpUtils();
        SDKInitializer.initialize(this);
        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);
        initSmartRefreshLayout();
        StyledDialog.init(this);
        initLoggerLevel();
        initLeakCanary();
        initBugly();
        SophixManager.getInstance().queryAndLoadNewPatch();

    }

    /**
     * 初始化腾讯的bugly
     */
    private void initBugly() {
        CrashReport.UserStrategy userStrategy = new CrashReport.UserStrategy(this);
        userStrategy.setAppVersion(PackageInfoUtils.getAppVersionName(this));
        //设置是否是开发模式
        CrashReport.setIsDevelopmentDevice(this, BuildConfig.DEBUG);
        ALog.d("当前bugly的调试模式是:" + BuildConfig.DEBUG);
        userStrategy.setCrashHandleCallback(new AppCrashHandleCallback());
        CrashReport.initCrashReport(getApplicationContext(), "85f09852f9", false, userStrategy);
    }

    /**
     * 集成LeakCanary 便于检查内存泄漏
     */
    private void initLeakCanary() {
        LeakCanary.install(this);
    }

    /**
     * 集成阿里的热修复
     */
    private void initSophix() {
        String appVersion = null;
        try {
            appVersion = this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName;
        } catch (Exception e) {
            appVersion = "3.1.1";
        }
        SophixManager.getInstance().setContext(this)
                .setAppVersion(appVersion)
                .setAesKey(null)
                .setEnableDebug(true)
                .setPatchLoadStatusStub(new PatchLoadStatusListener() {
                    @Override
                    public void onLoad(final int mode, final int code, final String info, final int handlePatchVersion) {
                        // 补丁加载回调通知
                        if (code == PatchStatus.CODE_LOAD_SUCCESS) {
                            // 表明补丁加载成功
                        } else if (code == PatchStatus.CODE_LOAD_RELAUNCH) {
                            // 表明新补丁生效需要重启. 开发者可提示用户或者强制重启;
                            // 建议: 用户可以监听进入后台事件, 然后应用自杀
                            getMainThreadHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    new AlertDialog.Builder(mContext).setMessage("检查到当前有新的补丁,必须重启应用进行生效").setPositiveButton("重启应用", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            SophixManager.getInstance().killProcessSafely();
                                        }
                                    }).show();
                                }
                            });
                        }
                    }
                }).initialize();
    }

    /**
     * 初始化okhttputils
     */
    private void initOkhttpUtils() {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
//                .addInterceptor(new LoggerInterceptor("TAG"))
                .connectTimeout(5000L, TimeUnit.MILLISECONDS)
                .readTimeout(5000L, TimeUnit.MILLISECONDS)
                //其他配置
                .build();

        OkHttpUtils.initClient(okHttpClient);
    }


    /**
     * 集成第三方下拉刷新的控件
     */
    private void initSmartRefreshLayout() {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreater(new DefaultRefreshHeaderCreater() {
            @NonNull
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                //指定为经典Header，默认是 贝塞尔雷达Header
                return new ClassicsHeader(context).setSpinnerStyle(SpinnerStyle.Translate);
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreater(new DefaultRefreshFooterCreater() {
            @NonNull
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setSpinnerStyle(SpinnerStyle.Translate);
            }
        });
    }

    /**
     * 初始化log等级设置
     * 如果是debug需要显示日志,release就不需要显示日志
     */
    private void initLoggerLevel() {
        if (com.hd.crdao.BuildConfig.DEBUG) {
            ALog.setLogLevel(ALog.LOG_LEVEL_ON);
        } else {
            ALog.setLogLevel(ALog.LOG_LEVEL_OFF);
        }
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        ALog.d("onTerminate 执行");
    }


}
